package com.liu.nb.controller;

import cn.hutool.captcha.LineCaptcha;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.map.MapUtil;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.liu.nb.dto.DaiBanDto;
import com.liu.nb.entity.Page;
import com.liu.nb.entity.SysUser;
import com.liu.nb.util.Const;
import com.liu.nb.util.Result;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.security.Principal;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;

/**
 * <p>
 * 用户表 前端控制器
 * </p>
 *
 * @author liuziyi,zk09-02添加方法
 * @since 2021-08-31
 */
@RestController
@RequestMapping("/nb/user")
public class UserController extends BaseController{
    /*
    * 获得用户的权限信息和导航栏
    * */
    @RequestMapping("/perms")
    public Result getUserPerms(Principal principal){
        SysUser byUsername = userService.getByUsername(principal.getName());
        /*获得用户的权限*/
        String userAuthorityInfo = userService.getUserAuthorityInfo(byUsername.getId());
        /*把用户权限转成数组*/
        String[] tokenize = StringUtils.tokenizeToStringArray(userAuthorityInfo, ",");
        /*获取用户导航栏信息*/
        List<Page> userNav = pageService.getUserNav(byUsername.getId());
        /*return一个map*/
        return Result.success(MapUtil.builder()
        .put("nav",userNav)
        .put("authorities",tokenize)
        .map());
    }
    /*
    * 获得用户信息（在登录成功之后跳转到首页的时候调用）
     */

    @RequestMapping("/getUserInfo")
    public Result getUserInfo(Principal principal){
        return Result.success(userService.getByUsername(principal.getName()));
    }
    /*
    * 修改密码
    * */
    @PostMapping("/changPassword")
    public Result changPassword(Principal principal,@RequestBody HashMap<String,String> map){
        Boolean changeUserPassword = userService.changeUserPassword(principal.getName(), map);
        return Result.success(changeUserPassword);
    }
    /*
    * 管理员修改用户资料
    * */
    @PostMapping("/changeUserInfo/root")
    public Result rootChangeUserInfo(@RequestBody SysUser user){
        boolean b = userService.updateById(user);
        return Result.success(b);
    }
    /*
    * 用户修改个人资料
    * 不允许修改用户名，用户名称，入职日期，离职日期
    * */
    @PostMapping("/changUserInfo/user")                         /*hashMap内有三个参数，分别是：新密码 ，旧密码 ，用户对象*/
    public Result userChange(Principal principal ,@RequestBody HashMap<String,Object> hashMap){
        SysUser sysUser = userService.getByUsername(principal.getName());
        /*把map转成user对象*/
        HashMap changUser = (HashMap)hashMap.get("changUser");
        SysUser changInfo = JSON.parseObject(JSON.toJSONString(changUser), SysUser.class);
        /*修改密码，先判断旧密码是否正确*/
        boolean matches = passwordEncoder.matches( hashMap.get("oldPassword").toString(),sysUser.getPassword());
        if (!matches){
            return Result.success(false);
        }
        sysUser.setPassword(passwordEncoder.encode(hashMap.get("newPassword").toString()));
        sysUser.setAge(changInfo.getAge());
        sysUser.setPhone(changInfo.getPhone());
        sysUser.setEmail(changInfo.getEmail());
        sysUser.setGender(changInfo.getGender());
        boolean b = userService.updateById(sysUser);
        return Result.success(b);
    }

    /*
    * 系统管理员和线路管理员获得所有待办
    * */
    @PreAuthorize("hasAnyRole('root','xianluadmin')")
    @PostMapping("/getDanBan/root/{current}/{size}")
    public Result getDaiBan01(@PathVariable int current ,@PathVariable int size){
        IPage<DaiBanDto> daiBan = debugtaskService.getDaiBan(new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(current, size));
        return Result.success(daiBan);
    }
    /*
    * 巡检员获得待办
    * */
    @PreAuthorize("hasRole('xuanjianyuan')")
    @PostMapping("/getDaiBan/xuanjianyuan/{current}/{size}")
    public Result getDaiBan02(Principal principal,@PathVariable int current,@PathVariable int size){
        SysUser sysUser = userService.getByUsername(principal.getName());
        IPage<DaiBanDto> daiBanXunJian = debugtaskService.getDaiBanXunJian(new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(current, size), sysUser.getId());
        return Result.success(daiBanXunJian);
    }
    /*
    * 消缺员获得待办
    * */
    @PreAuthorize("hasRole('xiaoqueyuan')")
    @PostMapping("/getDaiBan/xiaoqueyuan/{current}/{size}")
    public Result getDaiBan03(Principal principal,@PathVariable int current,@PathVariable int size){
        SysUser sysUser = userService.getByUsername(principal.getName());
        IPage<DaiBanDto> iPage = debugtaskService.getDaiBanXiaoQue(new com.baomidou.mybatisplus.extension.plugins.pagination.Page<>(current, size), sysUser.getId());
        return Result.success(iPage);
    }
    //查询用户列表，可以根据用户名和状态筛选
    @PostMapping("/getUser/{pageCurrent}/{pageSize}")
    public Result getUser(@PathVariable Integer pageCurrent,@PathVariable Integer pageSize,
                           @RequestBody HashMap<String,String> map){
        Integer state=null;
        String name=map.get("name");
        String str= map.get("state");
        if(null!=str && str!=""){
            state = Integer.parseInt(str);
        }
        return Result.success(userService.getUser(pageCurrent,pageSize,name,state));
    }
    //添加用户
    @PostMapping("/adduser")
    public Result addUser(@RequestBody SysUser user){
        user.setPassword(passwordEncoder.encode(user.getPassword()));
        user.setJoindate(LocalDateTime.now());
        boolean save = userService.save(user);
        return Result.success(save);
    }
    //删除用户
    @PostMapping("/deluser/{id}")
    public Result deleteUser(@PathVariable int id){
        return Result.success(userService.removeById(id));
    }
    //修改用户
    @PostMapping("/upduser")
    public Result updUser(@RequestBody SysUser user){
        return Result.success(userService.updateById(user));
    }

    //更改用户状态
    @PostMapping("/updstate/{id}")
    public Result updState(@PathVariable int id){
        SysUser user = userService.getById(id);
        Integer state=null;
        //获取原来的用户状态并更新，原来是0则更新后是1，
        if(user.getState()==0){
            state=1;
        }else {
            state=0;
        }
        SysUser u=new SysUser();
        u.setState(state);
        u.setId(id);
        return Result.success(userService.updateById(u));
    }
    //登录后主页获得用户信息
    @RequestMapping("/getHeadInfo")
    public Result getHeadInfo(Principal principal){
        return Result.success(userService.getUserInfoByName(principal.getName()));
    }
    @RequestMapping("/captcha")
//    获取验证码
    public Result getCaptcha(){
        LineCaptcha lineCaptcha = new LineCaptcha(90, 40);
        String key = UUID.randomUUID().toString();
        String base64Img=lineCaptcha.getImageBase64Data();
        String captchaVal=lineCaptcha.getCode();
//        hset()的第一个参数是map的名字，第二个是map中的键的名字，第三个是键对应的值
        super.redisUtil.hset(Const.CAPTCHA_KEY,key,captchaVal,120);
        return Result.success(MapUtil.builder()
                .put("token",key)
                .put("captchaImg",base64Img)
                .build()
        );
    }
}

